﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using BYRBBS.Model;
using System.Diagnostics;
using BYRBBS.Util;
using BYRForum.Binding.Thread;

namespace BYRForum
{
    public partial class MainPage : PhoneApplicationPage
    {
        public bool if_loaded = false;//用于记录数据是否已经请求，保证之请求一次，节省流量

        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!if_loaded)
            {
                TopTenListBox.ItemsSource = App.TopTenList.Items;
                //十大请求
                String myRequestUrl = ByrApi.apiUrl + ByrApi.topten + ByrApi.Encode + ByrApi.appkey;
                RequestState state = new RequestState();
                HttpUtil.HttpGetWithParam(state, myRequestUrl, HttpWebRequset_TopTen_Callback);//发送请求
                progressBarWait.Visibility = Visibility.Visible;
                if_loaded = true;

                string mailUrl = ByrApi.apiUrl + "/mail/info" + ByrApi.Encode + ByrApi.appkey;
                RequestState mailState = new RequestState();
                HttpUtil.HttpGetWithParam(mailState, mailUrl, HttpWebRequset_MailInfo_Callback);

            }
        }

        #region TopTen
        //十大回调函数
        private void HttpWebRequset_TopTen_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                //网络有错误将会在这里抛出异常
                string result = HttpUtil.ReadToEndWithParam(asynchronousResult);
                Debug.WriteLine(result);
                string ErrorInfo;
                //如果没有错误，TopTen就是返回结果，ErrorInfo是空字符串
                //如果有错误，比如密码错误，这里TopTen返回为空结果，ErrorInfo是错误信息
                Widget TopTen = ParseUtil.ParseXml<Widget>(result, out ErrorInfo);
                if (TopTen == null)
                {
                    this.Dispatcher.BeginInvoke((Action)(() => {
                        MessageBox.Show(ErrorInfo);
                        progressBarWait.Visibility = Visibility.Collapsed;
                    }));
                }
                else
                {
                    this.Dispatcher.BeginInvoke((Action)(() => { 
                        App.TopTenList.LoadData(TopTen.Articles);
                        progressBarWait.Visibility = Visibility.Collapsed;
                    }));
                }
            }
            catch
            {
                Debug.WriteLine("Error");
                this.Dispatcher.BeginInvoke(() => {
                    progressBarWait.Visibility = Visibility.Collapsed;
                });
                //这里处理异常，可以在界面上抛出messagebox
            }
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ThreadsItem data = (sender as ListBox).SelectedItem as ThreadsItem;
            ListBoxItem selectedItem = (sender as ListBox).ItemContainerGenerator.ContainerFromItem(data) as ListBoxItem;

            int nSelect = (sender as ListBox).SelectedIndex;  //选择的项保存在 nSelect中
            //防止出错。
            if (-1 == nSelect)
            {
                return;
            }
            App.TempThreadItem = data;
            NavigationService.Navigate(new Uri("/BYRForum;component/ThreadsDetailPage.xaml", UriKind.Relative));
            (sender as ListBox).SelectedIndex = -1;  //最后设置整个ListBox控件选择为空，否则下次改变时获取的仍然是上次的值
        }
        #endregion

        #region Board Choose
        private void Campus_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.BoardChoose = 1;
            NavigationService.Navigate(new Uri("/BYRForum;component/BoardListPage.xaml?Section=北邮校园", UriKind.Relative));
        }

        private void Academic_Tech_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.BoardChoose = 2;
            NavigationService.Navigate(new Uri("/BYRForum;component/BoardListPage.xaml?Section=学术科技", UriKind.Relative));
        }

        private void Information_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.BoardChoose = 3;
            NavigationService.Navigate(new Uri("/BYRForum;component/BoardListPage.xaml?Section=信息社会", UriKind.Relative));
        }

        private void Art_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.BoardChoose = 4;
            NavigationService.Navigate(new Uri("/BYRForum;component/BoardListPage.xaml?Section=人文艺术", UriKind.Relative));
        }

        private void Life_Fashion_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.BoardChoose = 5;
            NavigationService.Navigate(new Uri("/BYRForum;component/BoardListPage.xaml?Section=生活时尚", UriKind.Relative));
        }

        private void Entertainment_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.BoardChoose = 6;
            NavigationService.Navigate(new Uri("/BYRForum;component/BoardListPage.xaml?Section=休闲娱乐", UriKind.Relative));
        }

        private void Sports_Exercise_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.BoardChoose = 7;
            NavigationService.Navigate(new Uri("/BYRForum;component/BoardListPage.xaml?Section=体育健身", UriKind.Relative));
        }

        private void Games_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            App.BoardChoose = 8;
            NavigationService.Navigate(new Uri("/BYRForum;component/BoardListPage.xaml?Section=游戏对战", UriKind.Relative));
        }
        #endregion

        #region Personal Page
        private void HttpWebRequset_MailInfo_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                //网络有错误将会在这里抛出异常
                string result = HttpUtil.ReadToEndWithParam(asynchronousResult);
                Debug.WriteLine(result);
                string ErrorInfo;
                //如果没有错误，TopTen就是返回结果，ErrorInfo是空字符串
                //如果有错误，比如密码错误，这里TopTen返回为空结果，ErrorInfo是错误信息
                MailInfo mailInfo = ParseUtil.ParseXml<MailInfo>(result, out ErrorInfo);
                if (mailInfo == null)
                {
                    this.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        MessageBox.Show(ErrorInfo);
                        progressBarWait.Visibility = Visibility.Collapsed;
                    }));
                }
                else
                {
                    this.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        //if (mailInfo.New_mail == "true")
                        //    InMailBox.Title = "有新邮件";
                        //else
                        //    InMailBox.Title = "收件箱";
                        progressBarWait.Visibility = Visibility.Collapsed;
                    }));
                }
            }
            catch
            {
                Debug.WriteLine("Error");
                this.Dispatcher.BeginInvoke(() =>
                {
                    progressBarWait.Visibility = Visibility.Collapsed;
                });
                //这里处理异常，可以在界面上抛出messagebox
            }
        }

        private void InMail_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/BYRForum;component/MailListPage.xaml?BoxName=收件箱&box=inbox", UriKind.Relative));
        }

        private void Out_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/BYRForum;component/MailListPage.xaml?BoxName=发件箱&box=outbox", UriKind.Relative));
        }

        private void Deleted_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/BYRForum;component/MailListPage.xaml?BoxName=垃圾箱&box=deleted", UriKind.Relative));
        }

        private void EditEmail_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/BYRForum;component/EditMailPage.xaml?from=main",UriKind.Relative));
        }

        private void Favourite_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/BYRForum;component/FavoritePage.xaml?level=0", UriKind.Relative));
        }

        private void Settings_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }
        #endregion

        #region About
        private void AboutUs_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/BYRForum;component/AboutUs.xaml", UriKind.Relative));
        }
        #endregion

        #region Help
        private void Help_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/BYRForum;component/Help.xaml", UriKind.Relative));
        }
        #endregion
        
        #region Quit
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("确认退出程序？", "退出", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
            {
                e.Cancel = true;
                return;
            }
            while (NavigationService.BackStack.Any())
                NavigationService.RemoveBackEntry();
        }
        #endregion
    }
}